<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="" prop="bitchName">
        <el-input v-model="queryParams.bitchName" placeholder="请输入标题" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <!-- <el-form-item label="创建时间">
        <el-date-picker v-model="daterangeCreateTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item> -->

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['exa:parper:add']">新增</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['exa:parper:edit']">修改</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['exa:parper:remove']">删除</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['exa:parper:export']">导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bitchList">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <!-- <el-table-column label="ID" align="center" prop="id" /> -->
      <el-table-column label="批次标题" align="center" prop="bitchName" :show-overflow-tooltip="true" />

      <el-table-column label="试卷名称" align="center" prop="parperName" :show-overflow-tooltip="true" />
      <el-table-column label="总分数" align="center" prop="score" />
      <el-table-column label="总人数" align="center" prop="peopleNum" />
      <el-table-column label="试题数" align="center" prop="parperNum" />
      <el-table-column label="单选题" align="center" prop="singleChoice" />
      <el-table-column label="多选题" align="center" prop="multipleChoice" />
      <el-table-column label="判断题" align="center" prop="judge" />
      <el-table-column label="简答题" align="center" prop="shortAnswer" />
      <el-table-column label="通过率" align="center" prop="passRate">
        <template slot-scope="scope">
          {{ scope.row.passRate }}%
        </template>
      </el-table-column>
      <!-- <el-table-column label="创建时间" align="center" prop="parperName" /> -->

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="small" plan type="text" @click="handleView(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加题目弹窗 -->
    <el-dialog title="数据统计" :visible.sync="open" width="880px" append-to-body>
      <div class="pre_dialog">
        <div class="pre_dialog_top">
          <div class="pre_dialog_top_l">{{ dialogData.exaParper.parperName }}</div>
          <div class="pre_dialog_top_r">共 {{ dialogData.exaParper.questionNum }} 题</div>
        </div>

        <div class="preContent" v-for="(question, qIndex) in dialogData.exaClassVoList" :key="qIndex"
          v-loading="loading2">
          <div class="tiMu">
            <!-- <div class="tiMu_top"> -->
            <!-- <div class="tiMuTitle">{{ question.exaParperClass.className }}</div> -->
            <!-- <div class="tiMuScore">(共{{ question.exaClassQuestionsList.length }}题／总计{{ getTiMuScore(question) }}分)
              </div> -->
            <!-- </div> -->
            <div class="shiTi" v-for="(item, index) in question.exaClassQuestionsList" :key="index">
              <div class="tiMuTitle">
                <div class="tiMuTitle_txt">
                  <span style="font-size: 18px;">{{ index + 1 }}.</span>
                  <span style="margin-left: 5px;">
                    {{ item.exaQuestionBankVo.exaQuestionBank.title }}
                  </span>
                </div>
                <!-- <div class="tiMuTitle_score">（{{ item.exaQuestionBankVo.exaQuestionBank.score }}分）</div> -->
              </div>

              <div class="tiMuOptions">
                <el-table :data="item.exaQuestionBankVo.exaQuestionOptionsList">
                  <el-table-column label="选项" align="left" :show-overflow-tooltip="true"
                    v-if="item.exaQuestionBankVo.exaQuestionBank.type != 4">
                    <template slot-scope="scope">
                      <span>
                        {{ String.fromCharCode(65 + scope.$index) }}. {{ scope.row.content }}
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column label="小计" align="center" prop="choiceNum" />
                  <el-table-column label="所占比例" align="center">
                    <template slot-scope="scope">
                      {{ scope.row.choiceRatio }}%
                    </template>
                  </el-table-column>
                </el-table>

                <div class="btns">
                  <el-button class="btnActive" icon="el-icon-s-fold" size="mini">表格</el-button>
                  <el-button :class="{ btnActive: activeChartType === 'pie' }" icon="el-icon-s-help" size="mini"
                    @click="switchChart('pie', item, qIndex, index)">饼状图</el-button>
                  <el-button :class="{ btnActive: activeChartType === 'bar' }" icon="el-icon-s-data" size="mini"
                    @click="switchChart('bar', item, qIndex, index)">柱状图</el-button>
                </div>

                <div class="ec">
                  <div :id="'chart-' + qIndex + '-' + index" style="width: 100%; height: 300px;"></div>
                </div>
              </div>

              <!-- <div class="tiMuOptions" v-if="item.exaQuestionBankVo.exaQuestionBank.type == 4">
                <div class="option" v-for="(option, oIndex) in item.exaQuestionBankVo.exaQuestionOptionsList"
                  :key="oIndex">
                  {{ option.oldContent ? option.oldContent : "未作答" }}

                </div>

                <div class="imgs" v-if="item.exaQuestionBankVo.exaQuestionBank.type == 4">
                  <img :src="baseUrl + item.exaQuestionBankVo.exaQuestionBank.images" mode="widthFix"></img>
                </div>

              </div> -->

              <!-- 正确答案 -->
              <!-- <div class="correctAnswer" v-if="item.exaQuestionBankVo.exaQuestionBank.type != 4">
                <span>正确答案：</span>
                <span style="color: #FF7600;">
                  {{
                    item.exaQuestionBankVo.exaQuestionOptionsList
                      .map((option, oIndex) => option.rorw ? String.fromCharCode(65 + oIndex) : '')
                      .filter(v => v)
                      .join('、')
                  }}
                </span>
              </div> -->
            </div>

          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <!-- <el-button type="primary" @click="submitForm2">确 定</el-button> -->
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listStatistics, getStatistics } from "@/api/exa/statistics"
import * as echarts from 'echarts'
export default {
  name: "Parper",
  dicts: ['parper_status', 'question_type'],
  data() {
    return {
      loading: true,
      loading2: false,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      bitchList: [],
      title: "",
      open: false,
      daterangeCreateTime: [],
      queryParams: { pageNum: 1, pageSize: 10, parperName: null, createBy: null, createTime: null },
      queryParams2: { pageNum: 1, pageSize: 10, title: null, score: null, type: null, createBy: null },
      form: {},

      dialogData: {
        exaParper: { parperName: null, questionNum: null, parperScore: null },
        exaClassVoList: []
      },

      charts: [], // 保存图表实例
      chartDom: null, // 当前图表容器
      activeChartType: '',
    }
  },
  created() {
    this.getList()
  },
  beforeDestroy() {
    // 销毁所有图表实例
    this.charts.forEach(chart => {
      chart.dispose()
    })
    this.charts = []
  },
  methods: {
    /** 查询试卷管理列表 */
    getList() {
      this.loading = true
      this.queryParams.params = {}
      if (this.daterangeCreateTime && this.daterangeCreateTime.length) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0]
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1]
      }
      listStatistics(this.queryParams).then(response => {
        console.log("getList", response);


        this.bitchList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    // 查看
    handleView(row) {
      this.form = row
      this.open = true
      this.loading2 = true

      let obj = {
        parperId: row.parperId,
        bitchId: row.bitchId,
        type: 1
      }
      getStatistics(obj).then(response => {
        this.loading2 = false
        this.dialogData = response.data

        // 数据加载完成后遍历显示柱状图
        this.$nextTick(() => {
          this.dialogData.exaClassVoList.forEach((question, qIndex) => {
            question.exaClassQuestionsList.forEach((item, index) => {
              this.handleBarChart(item, qIndex, index)
              this.activeChartType = 'bar' // 默认显示柱状图
            })
          })
        })
      })
    },

    switchChart(type, item, qIndex, index) {
      const key = `${qIndex}-${index}`
      this.activeChartType = type
      if (type === 'pie') {
        this.handlePieChart(item, qIndex, index)
      } else if (type === 'bar') {
        this.handleBarChart(item, qIndex, index)
      }
    },

    // 处理柱状图
    handleBarChart(item, qIndex, index) {
      console.log(item);

      this.$nextTick(() => {
        try {
          const chartId = `chart-${qIndex}-${index}`
          this.chartDom = document.getElementById(chartId)

          if (!this.chartDom) {
            console.error('找不到图表容器:', chartId)
            return
          }

          // 销毁已存在的图表实例
          const existingChart = echarts.getInstanceByDom(this.chartDom)
          if (existingChart) {
            existingChart.dispose()
          }

          const myChart = echarts.init(this.chartDom)

          const option = {
            title: {
              text: '选项统计'
            },
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'shadow' // 使用阴影指示器
              },
              formatter: '{b}: {c}人' // 添加百分比显示
            },
            xAxis: {
              type: 'category',
              data: item.exaQuestionBankVo.exaQuestionBank.histogram.xAxis.data,
              axisLabel: {
                interval: 0,  // 设置为 0 强制显示所有标签
                formatter: function (value, index) {
                  // 处理长文本换行
                  if (value.length > 10) {
                    return value.substring(0, 10) + '...';
                  }
                  return value;
                }
              }
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '15%',  // 增加底部空间放置标签
              containLabel: true
            },
            yAxis: {
              type: 'value'
            },
            series: [
              {
                data: item.exaQuestionBankVo.exaQuestionBank.histogram.yAxis.data,
                type: 'bar',
                barWidth: '30%',
                label: {
                  show: true,
                  position: 'top'
                }
              }
            ]
          }

          myChart.setOption(option)
          this.charts.push(myChart)

        } catch (error) {
          console.error('图表初始化失败:', error)
        }
      })
    },

    // 处理饼状图
    handlePieChart(item, qIndex, index) {
      console.log(item);


      this.$nextTick(() => {
        try {
          const chartId = `chart-${qIndex}-${index}`  // 使用传入的 qIndex 和 index
          const chartDom = document.getElementById(chartId)

          if (!chartDom) {
            console.error('找不到图表容器:', chartId)
            return
          }

          // 销毁已存在的图表实例
          const existingChart = echarts.getInstanceByDom(chartDom)
          if (existingChart) {
            existingChart.dispose()
          }

          const myChart = echarts.init(chartDom)

          const option = {
            // title: {
            //   text: '选项统计',
            //   left: 'center'
            // },
            tooltip: {
              trigger: 'item',
              formatter: '{b}: {c} ({d}%)'  // 添加百分比显示
            },
            // legend: {
            //   orient: 'vertical',
            //   left: 'left'
            // },
            series: [
              {
                name: '选项',
                type: 'pie',
                radius: '50%',
                data: item.exaQuestionBankVo.exaQuestionBank.data,
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                },
                label: {
                  show: true,
                  formatter: function (params) {
                    // 显示名称、人数和百分比
                    return `${params.name}\n${params.value}人 (${params.percent}%)`
                  }
                }
              }
            ]
          }

          myChart.setOption(option)
          this.charts.push(myChart)

        } catch (error) {
          console.error('图表初始化失败:', error)
        }
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    // 表单重置
    reset() {
      this.form = {
        exaParper: { id: null, parperName: null, questionNum: null, parperScore: null },
        exaClassVoList: []
      }
      this.resetForm("form")
    },

    // 搜索
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    // 重置
    resetQuery() {
      this.daterangeCreateTime = []
      this.resetForm("queryForm")
      this.handleQuery()
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      // console.log(selection);

      this.formList = selection
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    // 导出
    handleExport() {
      this.download('exa/parper/export', { ...this.queryParams }, `parper_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog {
  background-color: #F1F4F6;

  .pre_dialog {
    .pre_dialog_top {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 0;
      font-size: 16px;
      font-weight: bold;
      color: #333;
      border-bottom: 1px solid #ddd;
      // background-color: #fff;



    }

    .pre_dialog_top_content {
      padding: 20px;

      .tiMu {
        margin-bottom: 20px;

        .tiMuTitle {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 10px;
          background-color: #fff;
          border: 1px solid #ddd;
          border-radius: 4px;

          .tiMuTitle_l {
            font-size: 16px;
            font-weight: bold;
            color: #333;
          }

          .tiMuTitle_r {
            font-size: 14px;
            color: #666;
          }
        }
      }
    }
  }

}

.preContent {
  padding: 30px 0;
  box-sizing: border-box;

  .tiMu {
    // display: flex;
    // justify-content: space-between;
    // align-items: center;

    .tiMu_top {
      width: 97%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      font-size: 16px;


      .tiMuTitle {
        font-size: 16px;
        font-weight: bold;
        color: #403933;
      }

      .tiMuScore {
        font-size: 16px;
        color: #747474;
      }
    }

    .shiTi {
      width: 75%;
      margin: 0 auto;
      margin-bottom: 20px;
      padding: 10px;
      background-color: #fff;
      border-radius: 4px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

      .tiMuTitle {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;

        .tiMuTitle_txt {
          font-size: 16px;
          color: #333;
        }

        .tiMuTitle_score {
          font-size: 14px;
          color: #999;
        }
      }

      .tiMuOptions {
        .el-table {
          margin-bottom: 10px;

          &::before {
            height: 0;
          }

          .el-table__header-wrapper {
            th {
              background-color: #f5f7fa;
              color: #606266;
            }
          }
        }

        .btns {
          display: flex;
          justify-content: flex-end;
          align-items: center;
          color: #7F7F7F;

          .btnActive {
            background-color: #169BD5;
            color: #fff;
          }
        }
      }

      .correctAnswer {
        margin-top: 20px;
      }
    }
  }
}
</style>